﻿using FluentValidation;
using RockBus.DataContracts;
using System.Collections.Generic;

namespace RockBus.ConfigurationService.Validation
{
    public class SubscriberInfoValidator : AbstractValidator<SubscriberInfo>
    {
        public SubscriberInfoValidator()
        {
            this.RuleFor(x => x.Id).NotNull();
            this.RuleFor(x => x.Id).NotEmpty();
            //this.RuleFor(x => x.Namespaces).NotNull();
            //this.RuleFor(x => x.Namespaces).NotEmpty();
            //this.RuleFor(x => x.Namespaces).SetCollectionValidator(new NamespaceInfoValidator());
            this.RuleFor(x => x.EndpointInfoDictionary).NotNull();
            this.RuleFor(x => x.EndpointInfoDictionary).NotEmpty();
            this.RuleFor(x => x.EndpointInfoDictionary.Values).SetCollectionValidator(new EndpointInfoValidator());
            this.RuleFor(x => x.InfoDictionary).NotNull();
            this.RuleFor(x => x.InfoDictionary).NotEmpty();
            this.RuleFor(x => x.InfoDictionary.Values).SetCollectionValidator(new SubscriptionInfoValidator());
            this.RuleFor(x => x.InfoDictionary.Values).Must((sub, subs) => this.ReferToExistingEndpoints(sub, subs)).WithMessage("At least one SubscriptionInfo.EndpointId does not exist in the SubscriberInfo.EndpointInfoDictionary.");
        }

        private bool ReferToExistingEndpoints(SubscriberInfo subscriberInfo, IEnumerable<SubscriptionInfo> subscriptionInfos)
        {
            foreach (var si in subscriptionInfos)
            {
                if (!subscriberInfo.EndpointInfoDictionary.ContainsKey(si.Detail.EndpointId))
                {
                    return false;
                }
            }
            return true;
        }
    }
}